package com.jianbing.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.AccessToken;
import com.jianbing.entity.Customer;
import com.jianbing.entity.Result;
import com.jianbing.entity.TaskStatus;
import com.jianbing.service.NoticeDataWarehouseService;
import com.jianbing.service.ZXService;
import com.jianbing.util.Constants;
import com.jianbing.util.HttpClient;
import com.jianbing.util.SignUtil;
import com.jianbing.util.StringUtils;
import com.jianbing.util.TableUtil;
import com.mongodb.BasicDBObject;

import net.sf.json.JSONObject;

@Service
public class ZXServiceImpl implements ZXService {

	Logger logger = Logger.getLogger(ZXServiceImpl.class);

	@Autowired
	private NoticeDataWarehouseService noticeDataWarehouseService;

	@SuppressWarnings("static-access")
	@Override
	public Result getZxData(Result result, JSONObject json) throws Exception {
		ModelMap model = new ModelMap();
		Date now = new Date();
		JSONObject jsonParam = JSONObject.fromObject(json.get("params"));
		MongoDBDao dbDao = new MongoDBDao();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("appKey", jsonParam.get("appKey"));
		Customer customer = dbDao.findOne(TableUtil.customer, Customer.class, queryObject);
		if (customer == null) {
			result.setCode(102);
			result.setMsg("无效的appKey");
			return result;
		}
		AccessToken accessToken = MongoDBDao.findOne(TableUtil.accessToken, AccessToken.class, queryObject);
		if (accessToken == null || accessToken.getActiveTime() < now.getTime()) {
			result.setCode(103);
			result.setMsg("token已超时");
			return result;
		}
		if ((jsonParam.getLong("timestamp") + Constants.accessTime * 1000) < now.getTime()
				|| !SignUtil.checkSign(json.getString("sign"), jsonParam, customer.getAppSecret())) {
			result.setCode(104);
			result.setMsg("签名错误");
			return result;
		}
		// 从数据仓库获取数据并校验
		String zxDataResult = HttpClient.get(Constants.zx_data_url + jsonParam.getString("orderSn"));
		if (StringUtils.isEmpty(zxDataResult)) {
			result.setCode(105);
			result.setMsg("无此订单数据");
			return result;
		}
		JSONObject zxDataJson = JSONObject.fromObject(zxDataResult);
		// String name = zxDataJson.getString("姓名");
		// String ID = zxDataJson.getString("证件号码").replaceAll("x", "*");

		// if (StringUtils.isEmpty(name)
		// ||
		// !StringFuzzyMatchUtils.checkStringMatching2(jsonParam.getString("name"),
		// name)) {
		// result.setCode(106);
		// result.setMsg("姓名匹配失败");
		// return result;
		// }
		// if (StringUtils.isNotEmpty(ID) &&
		// (!IDCardUtil.IDCardValidate(jsonParam.getString("ID"))
		// ||
		// !StringFuzzyMatchUtils.checkStringMatching2(jsonParam.getString("ID"),
		// ID))) {
		// result.setCode(107);
		// result.setMsg("身份证号匹配失败");
		// return result;
		// }
		logger.info("征信数据查询成功" + zxDataResult);
		// 返回数据给合作方
		model.addAttribute("zxData", zxDataJson);
		result.setData(model);
		// 向数据仓库上传用户信息
		Map<String, Object> noticeMsg = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderid", jsonParam.getString("orderSn"));
		params.put("name", "");
		params.put("id", "");
		params.put("serviceType", "credit");
		noticeMsg.put("params", params);
		noticeMsg.put("url", Constants.data_notice_url);
		noticeDataWarehouseService.producer(JSONObject.fromObject(noticeMsg).toString());
		logger.info("通知数据仓库征信用户信息  success" + noticeMsg);
		return result;
	}

	@Override
	public List<TaskStatus> queryZxTaskStatus(String orderSn, Integer taskId, String status) {
		BasicDBObject queryObject = new BasicDBObject();
		if (StringUtils.isNotEmpty(orderSn)) {
			queryObject.append("orderSn", orderSn);
		}
		if (StringUtils.isNotEmpty(status)) {
			queryObject.append("status", status);
		}
		if (taskId != null) {
			queryObject.append("taskId", taskId);
		}
		List<TaskStatus> zxTaskStatusList = MongoDBDao.queryForList(TableUtil.zxTaskStatusTable, TaskStatus.class,
				queryObject, null, null, null, null);
		return zxTaskStatusList;
	}

	@Override
	public void updateZxTaskStatus(String orderSn, Integer taskId, String status) throws Exception {
		Date now = new Date();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("orderSn", orderSn);
		TaskStatus zxTaskStatus = MongoDBDao.findOne(TableUtil.zxTaskStatusTable, TaskStatus.class, queryObject);
		if (zxTaskStatus == null) {
			zxTaskStatus = new TaskStatus();
			zxTaskStatus.setOrderSn(orderSn);
			zxTaskStatus.setTaskId(taskId);
			zxTaskStatus.setStatus(status);
			zxTaskStatus.setCreateTime(now);
			zxTaskStatus.setUpdateTime(now);
			MongoDBDao.insert(TableUtil.zxTaskStatusTable, zxTaskStatus);
		} else {
			zxTaskStatus.setStatus(status);
			zxTaskStatus.setUpdateTime(now);
			zxTaskStatus.setTaskId(taskId);
			MongoDBDao.update(TableUtil.zxTaskStatusTable, queryObject, zxTaskStatus);
		}
	}
}
